package com.zwb.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwb.boot.common.R;
import com.zwb.boot.common.utils.ObjectConverter;
import com.zwb.boot.dto.OrderDetailDto;
import com.zwb.boot.dto.OrdersDto;
import com.zwb.boot.entity.OrderDetail;
import com.zwb.boot.entity.Orders;
import com.zwb.boot.service.OrderDetailService;
import com.zwb.boot.service.OrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 头发又黑又长
 * @Date 2022/7/26 19:17
 * @email zwb15083976291@163.com
 */
@Api("订单管理")
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @ApiOperation("用户下单接口")
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders,
                            HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute("user");
        orders.setUserId(userId);
        ordersService.submit(orders);
        return R.success("下单成功");
    }


    @ApiOperation("订单分页数据查询")
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(@RequestParam(required = false, defaultValue = "1") Integer page,
                                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                       HttpServletRequest request) throws Exception {
        Long userId = (Long) request.getSession().getAttribute("user");
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId)
                .orderByDesc(Orders::getOrderTime);
        ordersService.page(ordersPage, queryWrapper);

        // 转换为DTO
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<OrdersDto> ordersDtos = ObjectConverter.collectionBeanConverter(ordersPage.getRecords(), OrdersDto.class);

        // 查询订单详情
        for (OrdersDto item : ordersDtos) {
            List<OrderDetail> orderDetails = orderDetailService.findByOrderId(item.getId());
            List<OrderDetailDto> orderDetailDtos = ObjectConverter.collectionBeanConverter(orderDetails, OrderDetailDto.class);
            item.setOrderDetails(orderDetailDtos);
            item.setSumNum(orderDetailDtos.size());
        }
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }


}
